package com.atguigu.tingshu.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/***
 * 自定义feign拦截器 全局拦截器
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * feign执行之前进行触发
     *
     * @param requestTemplate 请求模板
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前线程的请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // request不为空
        if (requestAttributes != null) {
            // 获取原请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 获取原请求对象头中的全部数据
            Enumeration<String> headerNames = request.getHeaderNames();
            // 循环
            while (headerNames.hasMoreElements()) {
                // 获取请求头名字
                String name = headerNames.nextElement();
                // 获取请求头的值
                String value = request.getHeader(name);
                // 存储
                requestTemplate.header(name, value);
            }
        }
    }
}